﻿using FreeSql.Internal.ObjectPool;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using PropertyChanged;
using sys_Print.Common;
using sys_Print.DataAsset;
using sys_Print.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using static FreeSql.Internal.GlobalFilter;

namespace sys_Print.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class ModelTypeEntryViewModel : ViewModelBase
    {
        [DoNotNotify]
        private readonly IFreeSql _fsql;

        public List<string> ControlTypes { get; set; }
        public List<DataDictionary> ProjectNames { get; set; }
        public ObservableCollection<PrintCanvasModel> DataList { get; set; } = new ObservableCollection<PrintCanvasModel>();
        public List<PrintModelType> ComboBoxList { get; set; } = new List<PrintModelType>();
        public PrintModelType selectedPrintModelType { get; set; }
        public int SelectedItemIndex { get; set; }
        public RelayCommand DropDownOpenedCommand { get; private set; }
        public RelayCommand DropDownClosedCommand { get; private set; }
        public RelayCommand SubmitButtonCommand { get; private set; }
        public RelayCommand AddButtonCommand { get; private set; }
        public RelayCommand RefreshButtonCommand { get; private set; }
        public RelayCommand<DataGridRow> DeleteButtonCommand { get; private set; }


        public ModelTypeEntryViewModel() 
        {
            // 获取配置好的FreeSql实例
            _fsql = App.FsqlDB;

            DropDownOpenedCommand = new RelayCommand(new Action(CommandDropDownOpened));
            DropDownClosedCommand = new RelayCommand(new Action(CommandDropDownClosed));
            SubmitButtonCommand = new RelayCommand(new Action(OnSubmitButton));
            AddButtonCommand = new RelayCommand(new Action(OnAddButton));
            RefreshButtonCommand = new RelayCommand(new Action(CommandDropDownClosed));
            DeleteButtonCommand = new RelayCommand<DataGridRow>(new Action<DataGridRow>(OnDeleteButton));

            ProjectNames = _fsql.Select<DataDictionary>().Where(a => a.Priority == 1).OrderByDescending(a => a.OptionName).ToList();

            ControlTypes = new EmployeeTemplateSelector().GetPropertyNames();
        }


        private void OnDeleteButton(DataGridRow row)
        {
            if (row != null && row.DataContext is PrintCanvasModel dataItem)
            {
                SelectedItemIndex = -1;
                DataList.Remove(dataItem);

                _fsql.Delete<PrintCanvasModel>().Where(dataItem).ExecuteAffrows();
            }            
        }

        private void OnAddButton()
        {
            if (selectedPrintModelType == null)
            {
                HandyControl.Controls.Growl.Warning("请选择框架模板！");
                return;
            }

            DataList.Add(new PrintCanvasModel()
            {
                OrderNo = DataList.Count + 1 ,
                ModelId = selectedPrintModelType.Id,
                IsdisplayKeyword = true,
                TaskChange = false,
                MeterChange = false,
                CoordinateX = 0, 
                CoordinateY = 0,
                Width = 0,

            });
        }

        private void OnSubmitButton()
        {
            if (selectedPrintModelType == null)
            {
                HandyControl.Controls.Growl.Warning("请选择框架模板！");
                return;
            }

            // 获取在 DataGrid 中所做的更改
            var modifiedItems = DataList.Where(item => item.IsChanged);

            if (modifiedItems == null)
            {
                return;
            }

            using (Object<DbConnection> conn = _fsql.Ado.MasterPool.Get())
            {
                using (DbTransaction transaction = conn.Value.BeginTransaction())
                {
                    try
                    {
                        foreach (PrintCanvasModel item in modifiedItems)
                        {
                            _fsql.InsertOrUpdate<PrintCanvasModel>().SetSource(item).WithTransaction(transaction).ExecuteAffrows();

                            // 将更改标记为已提交
                            item.AcceptChanges();
                        }

                        transaction.Commit();
                        HandyControl.Controls.Growl.Info("提交完成！");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        //记录日志，抛出异常（使用全局异常）或者返回自定义数据 
                        throw ex;
                    }
                }
            }

        }

        private void CommandDropDownOpened()
        {
            ComboBoxList = _fsql.Select<PrintModelType>().Where(a => a.State == true).ToList();
        }

        private void CommandDropDownClosed()
        {
            if (selectedPrintModelType == null)
            {
                HandyControl.Controls.Growl.Warning("请选择框架模板！");
                return;
            }
            List<PrintCanvasModel> list = _fsql.Select<PrintCanvasModel>().Where(a => a.ModelId == selectedPrintModelType.Id).OrderBy(a => a.OrderNo).ToList();
            DataList = new ObservableCollection<PrintCanvasModel>(list);
        }
    }
}
